﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace DSEngine.AnimationMaker
{
    public partial class MainForm : Form
    {
        AnimationEntity animation;
        List<string> files = new List<string>();
        List<string> frame = new List<string>();
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {

        }
        void UpdateList()
        {
            fileList.Items.Clear();
            animeList.Items.Clear();

            fileList.Items.AddRange(files.ToArray());
            animeList.Items.AddRange(frame.ToArray());

            number.Text = files.Count.ToString() + "张";
        }
        private void 添加图片ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog opf = new OpenFileDialog())
            {
                opf.Multiselect = true;
                opf.Filter = "*.PNG|*.png";
                if (opf.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                   
                    foreach (var item in opf.FileNames)
                    {
                        frame.Add(item);
                        if (files.Contains(item) == false)
                        {
                            files.Add(item);
                        }
                    }
                    UpdateList();
                }
            }
        }

        private void 导出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int i=1;
            
            animation = new AnimationEntity();
            animation.frames = new List<Frame>();
            foreach (var item in files)
            {
                Frame f = new Frame();
                f.name = "frame"+i.ToString();
                i++;
                f.offset = new Offset();
                f.size = new Size();
                animation.frames.Add(f);
            }

            int row, col;
            row = col = 0;
            int count = files.Count;
            int left = 0;
            col = (int)Math.Sqrt(count);
            left = count % col;
            row = count / col;
            if (left != 0)
            {
                row++;
            }

            int width, height;
            int cW, cH;

            List<Bitmap> bpList = new List<Bitmap>();
            width = height = cW = cH = 0;
            foreach (var item in files)
            {
                Bitmap bp = new Bitmap(item);
                bpList.Add(bp);
            }
            int index = 0;
            Bitmap[,] box = new Bitmap[row, col];
            for (int r = 0; r < row-1; r++)
            {
                for (int c = 0; c < col; c++)
                {
                    box[r, c] = bpList[index];
                    box[r, c].Tag = index;
                    index++;
                }
            }
            for (int j = 0; j < left; j++)
            {
                box[row-1, j] = bpList[index];
                box[row - 1, j].Tag = index;
                index++;
            }

            for (int r = 0; r < row; r++)
            {
                for (int c = 0; c < col; c++)
                {
                    if(box[r,c]!=null)
                    {
                        cW += box[r, c].Width;
                        if (cW > width)
                            width = cW;
                    }
                }
                cW = 0;
            }

            for (int c = 0; c < col; c++)
            {
                for (int r = 0; r < row; r++)
                {
                    if (box[r, c] != null)
                    {
                        cH += box[r, c].Height;
                        if (cH > height)
                            height = cH;
                    }
                }
                cH = 0;
            }

            Bitmap map = new Bitmap(width, height,System.Drawing.Imaging.PixelFormat.Format32bppArgb);
            Graphics g = Graphics.FromImage(map);
            float ix, iy;
            ix = iy = 0;
            int maxHeight=0;
            for (int r = 0; r < row; r++)
            {
                maxHeight = 0;
                ix = 0;
                for (int c = 0; c < col; c++)
                {
                    if (box[r, c] != null)
                    {
                        g.DrawImage(box[r, c], ix, iy);
                        UpdateFrame((int)box[r, c].Tag, ix, iy, width, height, box[r, c].Width, box[r, c].Height);
                        ix += box[r, c].Width;
                        if (maxHeight < box[r, c].Height)
                            maxHeight = box[r, c].Height;

                    }
                }
                iy += maxHeight;
            }
            animation.animations = new Animation();
            animation.animations.loops = checkBox1.Checked;
            animation.animations.name = textBox1.Text;
            animation.animations.smooth = false;
            animation.animations.key_frames = new List<KeyFrame>();
            foreach (var item in frame)
            {
                index = files.IndexOf(item);
                KeyFrame kf = new KeyFrame();
                double value = 0;
                double.TryParse(textBox1.Text, out value);
                kf.duration = value;
                kf.frame = animation.frames[index].name;
                animation.animations.key_frames.Add(kf);
            }
            g.Dispose();
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.Filter = "*.animation|*.animation";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string path = System.IO.Path.GetDirectoryName(sfd.FileName);
                    string fileName = System.IO.Path.GetFileNameWithoutExtension(sfd.FileName);
                    map.Save(System.IO.Path.Combine(path, fileName + "_texture.png"), System.Drawing.Imaging.ImageFormat.Png);
                    Newtonsoft.Json.JsonSerializer js = new Newtonsoft.Json.JsonSerializer();
                    FileStream fs =  File.OpenWrite(sfd.FileName);
                    StreamWriter sw = new StreamWriter(fs);
                    js.Serialize(sw, animation);
                    sw.Close();
                }
            }

            files.Clear();
            frame.Clear(); 
        }
        void UpdateFrame(int index, float x, float y, float w, float h, float fw, float fh)
        {
            animation.frames[index].offset.x = x / w;
            animation.frames[index].offset.y = y / h;
            animation.frames[index].size.x = fw / w;
            animation.frames[index].size.y = fh / h;
        }

    }
}
